package com.ruoyi.service.project.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.LocalDateUtils;
import com.ruoyi.service.project.entity.ProjectSettleEntity;
import com.ruoyi.service.project.enums.SettleStatusEnum;
import com.ruoyi.service.project.mapper.ProjectSettleMapper;
import com.ruoyi.service.project.query.SettleQuery;
import com.ruoyi.service.project.service.ProjectSettleService;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 项目结算单 服务实现类
 * </p>
 *
 * @author Zane
 * @since 2025-10-26
 */
@Service
public class ProjectSettleServiceImpl extends ServiceImpl<ProjectSettleMapper, ProjectSettleEntity>
    implements ProjectSettleService {

  @Value("${kp.project.settle-project-limit-days:3}")
  private Integer settleProjectLimitDays;

  @Override
  public List<ProjectSettleEntity> getNeedSettleList() {
    //实现T+3日结算,取出三日前的项目结算单
    final LocalDateTime settleDate = LocalDateTime.now().minusDays(settleProjectLimitDays);
    return list(queryWrapper()
        .ge(ProjectSettleEntity::getCreateTime, LocalDateUtils.beginOfDate(settleDate))
        .le(ProjectSettleEntity::getCreateTime, LocalDateUtils.endOfDate(settleDate))
        .eq(ProjectSettleEntity::getSettleStatus, SettleStatusEnum.settling.getCode()));
  }

  @Override
  public BigDecimal getCommission() {
    return Optional.ofNullable(
            this.getBaseMapper().getCommission(SettleStatusEnum.settled.getCode()))
        .orElse(BigDecimal.ZERO);
  }

  @Override
  public Map<String, ProjectSettleEntity> mapByProjectIds(List<String> projectIds) {
    if (CollUtil.isEmpty(projectIds)) {
      return new HashMap<>();
    }
    return Optional.ofNullable(
        list(queryWrapper().in(ProjectSettleEntity::getProjectId, projectIds))).orElseGet(
        ArrayList::new).stream().collect(
        Collectors.toMap(ProjectSettleEntity::getProjectId, v -> v, (v1, v2) -> v1));
  }

  @Override
  public List<ProjectSettleEntity> demanderListSettle(SettleQuery settleQuery, Long userId) {
    return list(queryWrapper().orderByDesc(ProjectSettleEntity::getId)
        .eq(ProjectSettleEntity::getProjectManager, userId));
  }

  @Override
  public List<ProjectSettleEntity> platformListSettle(SettleQuery settleQuery) {
    return list(queryWrapper().orderByDesc(ProjectSettleEntity::getId));
  }

  private LambdaQueryWrapper<ProjectSettleEntity> queryWrapper() {
    return new LambdaQueryWrapper<>();
  }
}
